var sco = document.getElementById('score');
var time = document.getElementById('time');
var jieshu = document.getElementsByClassName('jieshu')[0];
var tr = document.getElementsByTagName('tr');
var start = document.getElementById('jia');
var flag=true;
tr[0].children[Math.ceil(Math.random() * 3) - 1].style.background = 'black';
tr[1].children[Math.ceil(Math.random() * 3) - 1].style.background = 'black';
tr[2].children[Math.ceil(Math.random() * 3) - 1].style.background = 'black';
tr[3].children[Math.ceil(Math.random() * 3) - 1].style.background = 'black';

var mis = 0;
var sec = 0;
var min = 0;
var score = 0;

var bool = true;
function addhang() {
    tb.insertRow(0);
    for (var i = 0; i < 3; i++) {
        tr[0].insertCell();
    }
    tr[0].children[Math.ceil(Math.random() * 3) - 1].style.background = 'black';
}

function del() {
    tr[4].remove();
}

document.documentElement.addEventListener('keydown', function (event) {
    if(flag){
        if (bool == true && (event.key == 'j' || event.key == 'k' || event.key == 'l')) {
            int = setInterval(times, 10);
            bool = false;
        }
        switch (event.key) {
            case 'j':
                if (tr[3].children[0].style.background == 'black') {
                    addhang()
                    del();
                    scores();
                } else {
                    over();
                    begin();
                }
                break;
            case 'k':
                if (tr[3].children[1].style.background == 'black') {
                    addhang()
                    del();
                    scores();
                } else {
                    over();
                    begin();
                }
                break;
            case 'l':
                if (tr[3].children[2].style.background == 'black') {
                    addhang()
                    del();
                    scores();
                } else {
                    over();
                    begin();
                }
                break;
        }
    }
});

function scores() {
    score += 10;
    sco.innerHTML = score;
}

function over() {
    flag=false;
    clearInterval(int);
    mis = 0;
    sec = 0;
    min = 0;
    score = 0;
    sco.innerHTML = score;
    bool = true;
    jieshu.style.display='block';
    var text = document.createTextNode('用时：' + time.innerHTML + '   你的分数：' + score)
    
    start.appendChild(text)

}

function begin() {
    time.innerHTML = (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec) + ":" + (mis < 10 ? "0" +
        mis : mis);
}

function times() {
    mis += 1;
    if (mis > 99) {
        mis = 0;
        sec += 1;
    }
    if (sec > 59) {
        sec = 0;
        min += 1;
    }
    if (min > 23) {
        min = 0;
    }
    begin();
}